package com.qinghua.blog.controller;

import com.qinghua.blog.NoFoundException;
import com.qinghua.blog.po.Blog;
import com.qinghua.blog.service.BlogService;
import com.qinghua.blog.service.TagService;
import com.qinghua.blog.service.TypeService;
import com.qinghua.blog.vo.BlogQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

//欢迎页面
@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService;
    @Autowired
    private TagService tagService;


    @GetMapping("/")
    public String index(@PageableDefault(size = 10,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable, Model model){

        model.addAttribute("page",blogService.listBlog(pageable));
        model.addAttribute("typeTops",typeService.findByTop(6));
        model.addAttribute("tagTops",tagService.getTagByTop(10));
        model.addAttribute("blogTops",blogService.findByTop(8));

        return "index";

    }
    @PostMapping("/search")
    public String search(@PageableDefault(size = 10,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable, @RequestParam String query,Model model){

        Page<Blog> page= blogService.listBlog("%"+query+"%",pageable);
        model.addAttribute("page",page);
        model.addAttribute("query",query);
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model){

        this.insView(id);

        Blog blog=blogService.getConvertBlog(id);

        model.addAttribute("blog",blog);

        return "blog";
    }

    //访问增加浏览次数
    public void insView(Long id){
        Blog blog=blogService.getBlog(id);
        blog.setViews(blog.getViews()+1);
        blogService.saveBlog(blog);
    }
    @GetMapping("/footer/newBlog")
    public String showNewblogList(Model model){

       List<Blog> blogList= blogService.findByTop(3);
       model.addAttribute("newBlogs",blogList);
       return "_fragments :: newblogList";
    }

    @GetMapping("/footer/admin/newBlog")
    public String showAdminblogList(Model model){

        List<Blog> blogList= blogService.findByTop(3);
        model.addAttribute("newBlogs",blogList);
        return "admin/_fragments_admin :: newblogList";

    }
    @GetMapping("/about")
    public String about(){
        return "about";
    }
}

